package client.netty;

import client.GpcResponseListener;
import client.TankClient;
import lombok.Data;
import newtank.data.ConnectionSignal;
import server.code.ResponseStatus;

import java.util.concurrent.TimeUnit;

@Data
public class Startup {

	private final NetWorkClient client;
	private GpcResponseListener listener;
	private TankClient tankClient;
	public Startup(String host, int port) {
		this.client = NetWorkClient.builder(host, port);
		Runtime.getRuntime().addShutdownHook(new Thread(new ShutDownThread()));
	}
	
	class ShutDownThread implements Runnable {

		@Override
		public void run() {
			try {
				System.out.println("正在关闭连接");
				client.close();
				System.out.println("连接已完毕，2秒后退出");
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}//模拟应用进程退出前的处理操作
		}
	}
	
	public void start() {
		tankClient = new TankClient();
		tankClient.setClient(this.client);
		listener = GpcResponseListener.getInstance(tankClient);
		try {
			this.client.start(tankClient);
			ConnectionSignal message = new ConnectionSignal();
			message.setStatus(200);
			message.setCode(ResponseStatus.bind);
			message.setContext("正发起请求连接");
			client.sendMessage(message);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public static void main(String[] args) {
		new Startup("127.0.0.1", 8000).start();
		//new Startup("127.0.0.1", 8000).start();
	}
	
}
